﻿#include "pch.h"
#include "threadpool.h"

ThreadPool::ThreadPool(size_t num_threads) {
  for (size_t i = 0; i < num_threads; i++) {
    threads_.emplace_back([this, i] {
      while (true) {
        function<void()> task;
        {
          unique_lock<mutex> lock(queue_mutex_);
          // 当前队列为空或者发送停止信号时，不再接受新的任务放入线程池执行
          cv_.wait(lock, [this] { return !tasks_.empty() || stop_; });

          if (stop_ && tasks_.empty()) {
            return;
          }

          task = std::move(tasks_.front());
          tasks_.pop();
        }
        task();
      }
    });
  }
}

ThreadPool::~ThreadPool() {
  {
    unique_lock<mutex> lock(queue_mutex_);
    stop_ = true;
  }

  std::cout << "ThreadPool::~ThreadPool()" << std::endl;

  // 通知所有等待的线程
  cv_.notify_all();

  for (auto &thread : threads_) {
    thread.join();
  }

#if _DEBUG
  std::cout << u8"Thread Pool finish..." << std::endl;
#endif
}

/**
 * 执行异步任务
 * @brief ThreadPool::enqueue
 * @param task
 */
void ThreadPool::enqueue(function<void()> task) {
  {
    unique_lock<mutex> lock(queue_mutex_);
    tasks_.emplace(std::move(task));
  }
  cv_.notify_one();
}
